package com.foreveross.chameleon.mdm;

import android.app.Activity;
import android.app.Application;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import com.foreveross.chameleon.base.PushApplication;
import com.foreveross.chameleon.utils.AppLog;

/**
 * project:
 * author: wzq
 * date: 2014/7/31
 * description:
 */
public class MdmCmdExecutor {

    public final static String TAG = "MdmCmdExecutor";
    public static final int REQUEST_CODE_MDM = 10;
    private DevicePolicyManager dPM;
    private ComponentName adminName;

    private MdmCmdExecutor() {
        Application app = PushApplication.getApplication();
        dPM = (DevicePolicyManager) app.getSystemService(Context.DEVICE_POLICY_SERVICE);
        adminName = new ComponentName(app, BslDeviceAdmin.class);
    }

    private static MdmCmdExecutor instance = new MdmCmdExecutor();

    public static MdmCmdExecutor getInstance() {
        return instance;
    }

    public boolean isActive() {
        return dPM.isAdminActive(adminName);
    }

    public ComponentName getAdminName() {
        return adminName;
    }

    public DevicePolicyManager getDpm() {
        return dPM;
    }

    public void active(Activity act) {
        if (!isActive()) {
            AppLog.i(TAG, "激活mdm,act=" + act.getClass().getName());
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminName);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "点击 Activate按钮,激活MDM");
            act.startActivityForResult(intent, REQUEST_CODE_MDM);
        }
    }

    // 某些命令的值
    public static String alpha_digit = "alpha_digit";
    public static String alpha_digit_symbol = "alpha_digit_symbol";

    /**
     * @param cmd 需要执行的命令
     * @return true 表示执行成功,false失败
     * @throws Exception 有些操作可能失败
     */
    public boolean exec(ModelMdmCmd cmd) throws Exception {
        AppLog.i(TAG, "开始执行 mdm type=" + cmd.cmdType.toString() + ",arg=" + cmd.cmdArg);
        switch (cmd.cmdType) {
            case password_reset:
                boolean isSucc = dPM.resetPassword(cmd.cmdArg, 0);
                if (!isSucc) {
                    AppLog.e("mdm 执行失败,系统API 失败");
                }
                break;
            case password_min_len:
                int minLen = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordMinimumLength(adminName, minLen);
                resetPwdIfNecessary();
                break;
            case password_quality:
                if (alpha_digit_symbol.equals((cmd.cmdArg))) {
                    dPM.setPasswordQuality(adminName, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
                } else if (alpha_digit.equals(cmd.cmdArg)) {
                    dPM.setPasswordQuality(adminName, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
                } else {
                    AppLog.e("password_quality 参数不支持,args=" + cmd.cmdArg);
                }
                resetPwdIfNecessary();
            case password_min_letter:
                int minLenLetter = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordMinimumLetters(adminName, minLenLetter);
                resetPwdIfNecessary();
                break;
            case password_min_letter_low:
                int minLenLow = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordMinimumLowerCase(adminName, minLenLow);
                resetPwdIfNecessary();
                break;
            case password_min_digit:
                int minDigitLen = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordMinimumNumeric(adminName, minDigitLen);
                resetPwdIfNecessary();
                break;
            case password_min_letter_cap:
                int minLenCap = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordMinimumUpperCase(adminName, minLenCap);
                resetPwdIfNecessary();
                break;
            case password_expire_time:
                int expireTimeout = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordExpirationTimeout(adminName, expireTimeout);
                break;
            case password_history_restrict:
                int newPwdMinLen = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordHistoryLength(adminName, newPwdMinLen);
                break;
            case password_max_fail:
                int maxFail = Integer.parseInt(cmd.cmdArg);
                dPM.setMaximumFailedPasswordsForWipe(adminName, maxFail);
                break;
            case lock_screen:
                dPM.lockNow();// 锁屏
                break;
            case timeout_screen:
                int screeTimeout = Integer.parseInt(cmd.cmdArg);
                dPM.setMaximumTimeToLock(adminName, screeTimeout);
                break;
            case camera_disable:
                boolean isDisableCamera = "true".equalsIgnoreCase(cmd.cmdArg);
                dPM.setCameraDisabled(adminName, isDisableCamera);
                break;
            case storage_crypt:
                boolean isEncrypt = "true".equalsIgnoreCase(cmd.cmdArg);
                if (DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED == dPM.getStorageEncryptionStatus()) {
                    AppLog.e("不支持存储加密");
                    break;
                }
                dPM.setStorageEncryption(adminName, isEncrypt);
                if (isEncrypt && DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE != dPM.getStorageEncryptionStatus()) {
                    AppLog.e("存储加密失败");
                } else if (!isEncrypt && DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE != dPM.getStorageEncryptionStatus()) {
                    AppLog.e("存储加密失败");
                }
                break;
            case wipe_data:
                dPM.wipeData(0);
                break;
            case get_installed_applist: //获取本机安装的程序信息列表
                LocalInstalledAppInfoUtil.getInstance().execSubmitAppInfo();
                break;
            case uninstall_app:
                uninstallApp(cmd.cmdArg);
                break;
            case get_device_info:
                DeviceInfoMgr.getInstance().execSubmitDeviceInfo();
                break;
            case install_app:
                InstallMgr.getInstance().downloadFileByUrl(cmd.cmdArg);
                break;

            case password_min_symbol:
                int minLenSym = Integer.parseInt(cmd.cmdArg);
                dPM.setPasswordMinimumSymbols(adminName, minLenSym);
                resetPwdIfNecessary();
                break;
//            case password_require:
//                // 密码长度最小1，会影响之前的长度设置，因此不可行
//                dPM.setPasswordMinimumLength(adminName, 1);
//                resetPwdIfNecessary();
//                break;

            case device_config:
                new InstallConfig().exe(cmd.cmdArg);
                break;

            default: // 该命令不存在
                AppLog.e(TAG, "未找到的命令:" + cmd.cmdType.toString());
                return false;
        }
        return true;
    }

    private void uninstallApp(String packageName) {
        Application app = PushApplication.getApplication();
        android.content.pm.PackageManager pm = app.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(packageName, 0);
            if (info == null) {
                AppLog.e("uninstall app: pkg not exist " + packageName);
            } else {
                Uri uri = Uri.parse("package:" + packageName);
                Intent intent = new Intent(Intent.ACTION_DELETE, uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                app.startActivity(intent);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果需要则重设密码
     */
    private void resetPwdIfNecessary() {
        boolean isOk = dPM.isActivePasswordSufficient();
        if (isOk) {
            return;
        }
        Application app = PushApplication.getApplication();
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
        try {
            app.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
